require(["jquery", "paging", "template", "bootstrap", "echarts", "bbcare", "scprit/department/view/template/follow-up/common.js"], function($, Paging, template, bootstrap, echarts, $bb, $common) {

    var URL = $bb.baseUrl("followapp");
    var obj = $bb.getPageParams();
    var userId = obj.babyId || obj.userId,
        type = 'Gesell'; //历史记录传参;
    var count = 1,
        pagesize = 16;
    'use strict';
    var HashMap = $common.hashmap(),
        hashMap = new HashMap();

    var allPostion;
    var months = [0.93, 1.87, 2.8, 3.73, 4.67, 5.6, 6.5, 7.5, 8.4, 9.3, 10.3, 11.2, 12.1, 13.1, 15, 18, 21, 24, 30, 36, 42, 48, 54, 60, 72];
    var weeks = [4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56]; //13.1月
    getBabyInfo();
    if ($(".mainCenter").parents(".assess-wrap").length > 0) {
        $(".mainCenterRightT").hide();
        $(".mainCenterRightC").hide();
    }
    getAllPostion();
    $common.date();
    $(".mask, .AddInformation").hide();
    $(".AddInformation h4 span").click(function(event) {
        $(".mask, .AddInformation").hide();
    });
    var account = eval('(' + sessionStorage.account + ')');
    var accountName = account.alias;
    $("#userName").html(accountName); //检查医生名字
    $("#nowTime").html($common.getNowFormatDate());

    function getBabyInfo() {
        $bb.ajax({
            url: URL + "service/evaluation/queryUserMassage",
            data: JSON.stringify({
                data: {
                    "channelType": "2",
                    "queueUserId": userId
                }
            }),
            success: function(data) {
                if (data.success) {
                    var babyInfo = data.data;
                    var babyData = $common.babyInfoDeal(babyInfo);
                    $common.infoInit({ "id": "#babyInfoList", "data": babyData });
                }
            }
        });
    }

    function getAllPostion() {
        $bb.ajax({
            url: URL + "service/evaluation/getPostion",
            async: false,
            data: JSON.stringify({
                data: {
                    "evaluationType": type, //评测类型；
                    "queueUserId": userId
                }
            }),
            success: function(data) {
                if (data.success) {
                    allPostion = data.data;
                    showPostion(allPostion, 1);
                }
            }
        });
    }

    $("#submitData").click(function() {
        if (!$.isEmptyObject(hashMap.map)) {
            var channelId = $bb.getChannelId();
            var doctorName = JSON.parse($bb.getSessionStorage("account")).alias;
            var userName = $("#name").html();
            var params = {
                "oprInfo": {
                    "opCode": "1126",
                    "opType": "0",
                    "opNote": "【" + doctorName + "】医生为【" + userName + "】患者上传Gesell评估数据",
                    "channelType": "2",
                    "channelId": channelId,
                },
                "evaluationType": "Gesell",
                "queueUserId": userId,
                "postionIds": JSON.stringify(hashMap)
            };
            if ($(".mainCenter").parents(".assess-wrap").length > 0) {
                var taskId = $(".mainCenter").parents(".assess-wrap").data("ptTaskId");
                $.extend(params, { "taskId": taskId });
            }
            $bb.ajax({
                url: URL + "service/evaluation/submitGetScore",
                data: JSON.stringify({
                    data: params
                }),
                success: function(data) {
                    // if (data.success) {
                    localStorage.setItem("GesellIntelligence", JSON.stringify(data.data));
                    if ($(".mainCenter").parents(".assess-wrap").length == 0) {
                        $bb.openPage("gesellHistoryRecord", obj);
                    } else {
                        $.get("page/assess/html/gesell/gesellIntelligenceResult.html", function(html) {
                            $(".assess-wrap").html(html);
                        });
                    }
                    //}
                }
            });
        } else {
            $bb.toastShow("问卷还没有做，请做完之后再提交", 1500);
        }
    });
    $.tabs = {
        init: function() {
            this.orgData = months; //s数据源
            this.showData = weeks;
            this.showNumber = 8; //每组显示X条数据
            this.groupIndex = 0; //当前租索引
            this.initStyle();
        },
        bind: function() {
            var _this = this;
            $(".tabs-ul li[group]").click(function() { //绑定分组的单击事件
                var group = $(this).attr("group");
                if (group == "prev") {
                    if (_this.groupIndex > 0) {
                        _this.groupIndex--;
                        _this.initStyle();

                    }
                } else if (group == "next") {
                    var maxGroupIndex = _this.orgData.length / _this.showNumber;
                    if (_this.orgData.length % _this.showNumber != 0) {
                        maxGroupIndex = parseInt(_this.orgData.length / _this.showNumber) + 1;
                    }
                    maxGroupIndex--;
                    if (_this.groupIndex < maxGroupIndex) {
                        _this.groupIndex++;
                        _this.initStyle();

                    }
                }
            });
            $(".tabs-ul li[item]").click(function() {
                var index = parseInt($(this).attr("item"));
                $(".tabs-ul li[item]").removeClass("active");
                $(this).addClass("active");
                showPostion(allPostion, months[index]);
            });
        },
        initStyle: function(itemIndex) {
            var _this = this,
                data = _this.orgData,
                showData = _this.showData,
                showNumber = _this.showNumber,
                count = data.length,
                groupIndex = _this.groupIndex,
                start = 0,
                end = 0,
                str = '<li group="prev"><a href="javascript:;">《</a></li>';
            start = groupIndex * showNumber;
            end = (groupIndex + 1) * showNumber;
            end > count ? (end = count) : '';
            for (var i = start; i < end; i++) {
                var cls = ' class=';
                if (i == start || i == itemIndex) {
                    cls += '"active" ';
                }
                var val;
                if (String(data[i]).indexOf(".") != "-1") {
                    val = showData[i] + "周";
                } else {
                    val = data[i] + "月";
                }
                str += '<li item="' + i + '" ' + cls + '><a href="javascript:;">' + val + '</a><i></i></li>';
            }
            str += '<li group="next"><a href="javascript:;">》</a></li>';
            $(".tabs-ul").html(str);
            this.bind();
            showPostion(allPostion, months[start]);
        },
        changeTabs: function(index) {}
    };
    $.tabs.init();

    function setResult() {
        var obj = $bb.getPageParams();
        if (obj.result) {
            var result = JSON.parse(obj.result);
            var resultMap = result["map"];
            var arr = [];
            for (var item in resultMap) {
                var obj = {};
                obj.id = item;
                obj.tab = resultMap[item];
                arr.push(obj);
            }
            for (var i = 0; i < arr.length; i++) {
                var $this = $('div#' + arr[i].id + '.td-chd');
                $this.unbind('click');
                $("div#" + arr[i].id + ".td-chd li").unbind('click');
                var dataTab = arr[i].tab;
                var slectDiv = '';
                switch (dataTab) {
                    case '+':
                        slectDiv = '<li class="teststyle testbgclr3EB740" data-tab="+">+</li>';
                        break;
                    case '-':
                        slectDiv = '<li class="teststyle testbgclrE96052" data-tab="-">-</li>';
                        break;
                    case '+-':
                        slectDiv = '<li class="teststyle testbgclr89B9D1" data-tab="+-">+-</li>';
                        break;
                    case '++':
                        slectDiv = '<li class="teststyle testbgclr177A1A" data-tab="++">++</li>';
                        break;
                    case 'N':
                        slectDiv = '<li class="teststyle testbgclr3AAFA5" data-tab="N">N</li>';
                        break;
                }
                $this.append(slectDiv);
            }
        }
    }

    function showPostion(allPostion, num) {
        var one, two, three, four, five;
        for (var i = 0; i < months.length; i++) {
            if (months[i] == num) {
                if (num < 3) {
                    one = months[0];
                    two = months[1];
                    three = months[2];
                    four = months[3];
                    five = months[4];
                } else if (num > 54) {
                    one = months[months.length - 5];
                    two = months[months.length - 4];
                    three = months[months.length - 3];
                    four = months[months.length - 2];
                    five = months[months.length - 1];
                } else {
                    one = months[i - 2];
                    two = months[i - 1];
                    three = months[i];
                    four = months[i + 1];
                    five = months[i + 2];
                }
            }
        }
        var showT = [one, two, three, four, five];
        for (var i = 0; i < showT.length; i++) {
            if (String(showT[i]).indexOf(".") != "-1") {
                var pos = months.indexOf(showT[i]);
                showT[i] = weeks[pos] + "周";
            } else {
                showT[i] = showT[i] + "月";
            }
        }
        var title = '<th>能区/智龄</th><th>' + showT[0] + '</th><th>' + showT[1] + '</th><th>' + showT[2] + '</th><th>' + showT[3] + '</th><th>' + showT[4] + '</th>';
        $("#showTitle").html(title);

        var bigMovementTab = '<tr>' + '<td>大运动</td>';
        var fineActionTab = '<tr>' + '<td>精细动作</td>';
        var adaptabilityTab = '<tr>' + '<td>适应能力</td>';
        var languageTab = '<tr>' + '<td>语言</td>';
        var socialBehaviorTab = '<tr>' + '<td>社交行为</td>';

        var arr = new Array(one, two, three, four, five);

        for (var j = 0; j < arr.length; j++) {
            $.each(allPostion, function(index, content) {
                var month = index;
                if (month + "" == arr[j] + "") {
                    var params = {
                        month: month,
                        bigMovement: content.bigMovement,
                        fineAction: content.fineAction,
                        adaptability: content.adaptability,
                        language: content.language,
                        socialBehavior: content.socialBehavior
                    }

                    bigMovementTab += '<td>';
                    for (var i = 0; i < params.bigMovement.length; i++) {
                        bigMovementTab += '<div tp="slect" class="td-chd" id="' + params.bigMovement[i].id + '">' + params.bigMovement[i].name + '</div>';
                    }
                    bigMovementTab += '</td>';

                    fineActionTab += '<td>';
                    for (var i = 0; i < params.fineAction.length; i++) {
                        fineActionTab += '<div tp="slect" class="td-chd" id="' + params.fineAction[i].id + '">' + params.fineAction[i].name + '</div>';
                    }
                    fineActionTab += '</td>';

                    adaptabilityTab += '<td>';
                    for (var i = 0; i < params.adaptability.length; i++) {
                        adaptabilityTab += '<div tp="slect" class="td-chd" id="' + params.adaptability[i].id + '">' + params.adaptability[i].name + '</div>';
                    }
                    adaptabilityTab += '</td>';

                    languageTab += '<td>';
                    for (var i = 0; i < params.language.length; i++) {
                        languageTab += '<div tp="slect" class="td-chd" id="' + params.language[i].id + '">' + params.language[i].name + '</div>';
                    }
                    languageTab += '</td>';

                    socialBehaviorTab += '<td>';
                    for (var i = 0; i < params.socialBehavior.length; i++) {
                        socialBehaviorTab += '<div tp="slect" class="td-chd" id="' + params.socialBehavior[i].id + '">' + params.socialBehavior[i].name + '</div>';
                    }
                    socialBehaviorTab += '</td>';
                }
            });
        }
        bigMovementTab += '</tr>';
        fineActionTab += '</tr>';
        adaptabilityTab += '</tr>';
        languageTab += '</tr>';
        socialBehaviorTab += '</tr>';
        $("#showPostion").html(bigMovementTab + fineActionTab + adaptabilityTab + languageTab + socialBehaviorTab);
        setTableStyle(num);
        setResult();
    }

    function setTableStyle(num) {
        //添加点击事件浮层
        if ($("#optionsLayer").length == 0) {
            $(".mainCenter").append('<ul id="optionsLayer" class="btns">' +
                '<li class="bgclr3EB740" data-tab="+">+</li>' +
                '<li class="bgclrE96052" data-tab="-">-</li>' +
                '<li class="bgclr89B9D1" data-tab="+-">+-</li>' +
                '<li class="bgclr177A1A" data-tab="++">++</li>' +
                '<li class="bgclr3AAFA5" data-tab="N">N</li>' +
                '<li class="bgclr999B9B" data-tab="X">X</li>' +
                '</ul>');
        }

        //评估点击事件
        $(".postiontable tr [tp=slect]").click(function() {
            var $this = $(this);
            $this.append($('#optionsLayer').data('slectId', $this.attr('id')).show());
            $this.find(".teststyle").remove();
            var height = $this.height();
            $this.find("li").css({ "height": height / 2 + "px", "line-height": height / 2 + "px" });
        });
        $(".mainCenter").on("click", "li[class*='bgclr']", function() {
            event.stopPropagation();
            var $this = $(this),
                tab = $this.data('tab'), //存储当前li元素data-tab的属性值；
                $slectDiv = $this.closest('.td-chd'),
                $parent = $this.closest('#optionsLayer'),
                slectId = $parent.data('slectId');
            $slectDiv.find('.teststyle').remove();
            switch (tab) {
                case '+':
                    $parent.hide();
                    hashMap.put(slectId, tab);
                    $slectDiv.append('<li class="teststyle testbgclr3EB740" data-tab="+">+</li>');
                    break;
                case '-':
                    $parent.hide();
                    hashMap.put(slectId, tab);
                    $slectDiv.append('<li class="teststyle testbgclrE96052" data-tab="-">-</li>');
                    break;
                case '+-':
                    $parent.hide();
                    hashMap.put(slectId, tab);
                    $slectDiv.append('<li class="teststyle testbgclr89B9D1" data-tab="+-">+-</li>');
                    break;
                case '++':
                    $parent.hide();
                    hashMap.put(slectId, tab);
                    $slectDiv.append('<li class="teststyle testbgclr177A1A" data-tab="++">++</li>');
                    break;
                case 'N':
                    $parent.hide();
                    hashMap.put(slectId, tab);
                    $slectDiv.append('<li class="teststyle testbgclr3AAFA5" data-tab="N">N</li>');
                    break;
                case 'X':
                    $parent.hide();
                    hashMap.remove(slectId);
                    break;
            }
        });

        //切换表格内容重新设置样式
        var index = 4;
        if (num == 0.93) index = 2;
        if (num == 1.87) index = 3;
        if (num == 60) index = 5;
        if (num == 72) index = 6;
        $(".postiontable tr th:nth-child(" + index + ")").each(function() { //循环table的每行（tr）
            $(this).css({ "background": "#2ab5c7", "color": "#FFF" });
        });
        $(".postiontable tr td:nth-child(" + index + ")").each(function() { //循环table的每行（tr）
            $(this).css({ "background": "#2ab5c7", "color": "#FFF" });
        });

        //添加问题选中样式
        $.each(hashMap.map, function(key, value) {
            if (value == '+') $("#" + key).append('<li class="teststyle testbgclr3EB740" data-tab="+">+</li>');
            if (value == '-') $("#" + key).append('<li class="teststyle testbgclrE96052" data-tab="-">-</li>');
            if (value == '+-') $("#" + key).append('<li class="teststyle testbgclr89B9D1" data-tab="+-">+-</li>');
            if (value == '++') $("#" + key).append('<li class="teststyle testbgclr177A1A" data-tab="++">++</li>');
            if (value == 'N') $("#" + key).append('<li class="teststyle testbgclr3AAFA5" data-tab="N">N</li>');
        });
    }
    //历史记录列表点击：
    $("#dataList").on('click', "ul[result]", function() {
        var data = eval("(" + hashMap.get($(this).attr("result")).replace(/\=/g, "\:") + ")");
        localStorage.setItem("GesellIntelligence", JSON.stringify(data));
        $bb.openPage("gesellHistoryRecord", obj);
    });
    //历史记录列表：
    function getBabyList() {
        $bb.ajax({
            url: URL + "service/evaluation/recordlist", //baby地址
            data: JSON.stringify({
                data: {
                    "evaluationType": type,
                    "channelType": "2",
                    "queueUserId": userId,
                }
            }),
            success: function(data) {
                if (data.rows) {
                    hashMap = new HashMap();
                    count = data.total;
                    var babyData = data.rows;
                    if (count == 0) {
                        $bb.toastShow("患者还未参与该项测评！");
                    }
                    var str = '';
                    for (var i = 0; i < data.rows.length; i++) {
                        var testDate = data.rows[i].createTime.substring(0, 10);

                        hashMap.put(data.rows[i].id, data.rows[i].result);
                        var pretermBirth = 37 * 7 > data.rows[i].pregnancyWeek ? "是" : "否";
                        var nowDate = $common.getNowFormatDate();
                        var monthAge = $common.DateDiff(nowDate, data.rows[i].birthday) / 30;
                        var weight = data.rows[i].birthWeight == undefined ? "未知" : data.rows[i].birthWeight + "(g)";
                        var doctorName = data.rows[i].doctorName == undefined ? "未知" : data.rows[i].doctorName;

                        str += "<ul class='clearfix' result='" + data.rows[i].id + "' >";
                        str += '<li>' + data.rows[i].userName + '</li>';
                        str += '<li>' + weight + '</li>';
                        str += '<li>' + data.rows[i].birthday + '</li>';
                        str += '<li>' + data.rows[i].pregnancyWeek + '(天)</li>';
                        str += '<li>' + pretermBirth + '</li>';
                        str += '<li>' + doctorName + '</li>';
                        str += '<li>' + data.rows[i].createTime + '</li>';
                        str += '</ul>';
                    }
                    $("#dataList").html(str);
                }
            }
        });
    }

});